package com.example.statistics.ui.purchase

import android.os.Bundle
import android.text.method.DigitsKeyListener
import android.view.View
import com.example.statistics.R
import com.example.statistics.bean.Customer
import com.example.statistics.bean.InventoryBean
import com.example.statistics.bean.PurchaseProductBean
import com.example.statistics.bean.ShipmentBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.ui.customer.CustomerListActivity
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.example.statistics.ex.afterTextChangedListener
import com.example.statistics.weight.TextProcessingView
import kotlinx.android.synthetic.main.activity_inventory_port_add.*
import org.jetbrains.anko.toast
import java.util.*

/**
 * 港口货物销售
 */
class PurchaseShipmentActivity : BaseActivity() {

    var purchaseProductBean: PurchaseProductBean? = null
    var customerId: Int? = null
    var salesId = 0

    override val title: String
        get() = "港口出货"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_inventory_port_add)

        val type = intent.getStringExtra(Constants.TYPE)
        val purchaseProductId = intent.getIntExtra(Constants.PURCHASE_PRODUCT_ID, 0)
        val salesBean = intent.getSerializableExtra(Constants.DATA) as ShipmentBean?

        if (purchaseProductId == 0) {
            finish()
            toast("获取商品信息失败")
            return
        }

        if (salesBean != null) {
            salesId = salesBean.ID
            customerId = salesBean.customerId
            tv_date.contentText = salesBean.date.goTimeFormat()
            tv_customer.contentText = salesBean.customerName
            tv_car.contentText = salesBean.car
            tv_number.contentText = salesBean.salesNumber.toString()
            tv_weight.contentText = salesBean.salesWeight.toString()
            tv_price.contentText = salesBean.salesPrice.toString()
            tv_total_price.contentText = salesBean.totalPrice.toString()
            tv_freight.contentText = salesBean.freight.display()
            tv_unloading_fee.contentText = salesBean.unloadingFee.display()
        } else {
            tv_date.contentText = Date().format()
        }

        httpGet<PurchaseProductBean>(UrlConfig.PURCHASE_PRODUCT_DATA, config = {
            listParams = listOf("id" to purchaseProductId)
            isShowDialog = true
        }) { bean ->
            purchaseProductBean = bean
            if (bean != null) {
                tv_product.contentText = bean.factoryNo + bean.productName
                tv_container_no.contentText = bean.containerNo
                tv_contract_no.contentText = bean.contractNo
                if (salesBean == null) {
                    tv_number.contentText = bean.inventoryNumber.toString()
                    tv_weight.contentText = bean.inventoryWeight.toString()
                    tv_total_price.contentText = bean.productTotalPrice.toString()
                }

            }
        }


        if (type == "入库") {
            tv_customer.contentText = "豫德源"
            tv_customer.style = TextProcessingView.STYLE_DISPLAY
            customerId = 1
           // tv_freight.visibility = View.VISIBLE
           // tv_unloading_fee.visibility = View.VISIBLE
        } else {
            tv_freight.visibility = View.GONE
            tv_unloading_fee.visibility = View.GONE
            tv_customer.style = TextProcessingView.STYLE_SELECTOR
            tv_customer.onContentClicked {
                activityForResult<CustomerListActivity>(Constants.DATA to Constants.SELECTOR) {
                    val customer = it?.getSerializableExtra(Constants.DATA) as Customer?
                    tv_customer.contentText = customer?.name
                    customerId = customer?.ID
                }
            }
        }


        tv_number.afterTextChangedListener { editable, _ ->
            //val number = editable.maxLimit(this, purchaseProductBean?.inventoryNumber?.toFloat())
            var number = 0
            if (editable.toString().isNumber()) {
                number = editable.toString().toInt()
            }
            val specification = getSpecification(purchaseProductBean?.specification)
            if (specification == 0.0) { //非定装，可录入重量
                tv_weight.keyListener = DigitsKeyListener.getInstance("0123456789.")
            } else {//定装
                tv_weight.keyListener = null
                tv_weight.contentText = specification.mulEx(number.toInt()).toString()
                val price = tv_price.contentText.orEmpty()
                if (price.isNotEmpty() && price.isNumber()) {
                    tv_total_price.contentText = price.toDouble().mulEx(number.toDouble()).toString()
                }
            }
        }


        tv_weight.afterTextChangedListener { editable, _ ->
            val specification = getSpecification(purchaseProductBean?.specification)
            if (specification != 0.0) { //定装
                return@afterTextChangedListener
            }
            var weight = 0.0
            if (editable.toString().isNumber()) {
                weight = editable.toString().toDouble()
            }
            // val weight = editable.maxLimit(this, purchaseProductBean?.inventoryWeight?.toFloat())
            val price = tv_price.contentText.orEmpty()
            if (tv_weight.keyListener != null && price.isNumber()) {
                tv_total_price.contentText = price.toDouble().mulEx(weight).toString()
            }
        }
        tv_price.afterTextChangedListener { editable, _ ->
            val price = editable.toString()
            val weight = tv_weight.contentText.orEmpty()
            val number = tv_number.contentText.orEmpty()
            if (price.isNumber()) {
                if (tv_weight.keyListener != null && weight.isNumber()) {
                    tv_total_price.contentText = price.toDouble().mulEx(weight.toDouble()).toString()
                } else if (tv_weight.keyListener == null && number.isNumber()) {
                    tv_total_price.contentText = price.toDouble().mulEx(number.toDouble()).toString()
                }
            }
        }


        topBarRightText("保存") {
            if (purchaseProductBean == null) {
                toast("")
                return@topBarRightText
            }
            if (tv_customer.isBlank() || tv_number.isBlank() || tv_price.isBlank()) {
                return@topBarRightText
            }
            val number = tv_number.contentText.orEmpty()
            purchaseProductBean?.let {

                val isSettlement = it.billTotalAmount in (it.settlementTotalAmount-2..it.settlementTotalAmount+2)
                if (number.toInt() == purchaseProductBean?.inventoryNumber && !isSettlement) {
                    toast("请完成结算单")
                    return@topBarRightText
                }
            }

            val url = if (salesId == 0) {
                UrlConfig.PURCHASE_SALES_ADD
            } else {
                UrlConfig.PURCHASE_SALES_UPDATE
            }


            httpPost<InventoryBean>(url, config = {
                isShowDialog = true
                listParams = listOf(
                    "ID" to salesId,
                    "type" to type,
                    "customerId" to customerId,
                    "purchaseProductId" to purchaseProductBean!!.ID,
                    "productId" to purchaseProductBean!!.productId,
                    "date" to tv_date.contentText,
                    "car" to tv_car.contentText,
                    "salesPrice" to tv_price.contentText,
                    "salesNumber" to tv_number.contentText,
                    "salesWeight" to tv_weight.contentText,
                    "totalPrice" to tv_total_price.contentText,
                    "freight" to tv_freight.contentText,
                    "unloadingFee" to tv_unloading_fee.contentText,
                    "discountAmount" to 0,
                    "paymentAmount" to tv_total_price.contentText,
                )
            }) {
                activityFinish()
            }
        }
    }

    private fun getSpecification(str: String?): Double {
        val specification = str?.uppercase(Locale.getDefault())?.replace("KG", "")?.trim()
        return if (specification.isNumber())
            specification?.toDouble() ?: 0.0
        else
            0.0
    }
}